<template>
  <div class="login-container">
    <div class="loginBox">
        <div class="login_head">
          <img src="../assets/logo.png" alt="">
        </div>
<!--        登录表单区域-->
      <el-form ref="formRef" :model="form" :rules="rules" class="login_form" >
        <el-form-item prop="username">
          <el-input v-model="form.username"  prefix-icon="el-icon-user-solid"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item class="btn">
          <el-button type="info" @click="resetForm">重置</el-button>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {getLogin} from "@/utils/loginAPI";
export default {
  name: "Login",
  data(){
    return{
      form:{
        username:'admin',
        password:'123456',
      },
      rules:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  methods:{
    resetForm(){
      this.$refs.formRef.resetFields();
    },
    login(){
      this.$refs.formRef.validate(async valid=>{
        //通过表单验证返回true 不通过返回false
        // console.log(valid);
        //如果不通过的话 直接结束
        if(!valid) return;
        //通过
        const {data:res}=await getLogin(this.form);
        // console.log(res);
        if(res.meta.status!==200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        //登录成功后保存token
        window.sessionStorage.setItem('token',res.data.token);

        //跳转到home页面
        await this.$router.push('/home');
      })
    }
  }
}
</script>

<style scoped lang="less">
  .login-container{
    background-color: darkgray;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    .loginBox{
      width: 450px;
      height: 300px;
      background-color: white;
      position: relative;
      .login_head{
        position: absolute;
        width: 130px;
        height: 130px;
        border-radius: 50%;
        border: 1px solid #ddd;
        padding: 10px;
        left: 50%;
        background-color: white;
        transform: translate(-50%,-50%);
        img{
          width: 100%;
          height: 100%;
          border-radius: 50%;
          background-color: #eee;
        }
      }
      .login_form{
        position: absolute;
        bottom: 0;
        width: 100%;
        padding: 0 10px;
        box-sizing: border-box;
        .btn{
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
</style>
